package mysql

import (
"context"
"go.uber.org/zap"
"golang-sgg-daijia/internal/model"
	"time"
)

type DriverFaceRecognitionDao interface {
	Create(ctx context.Context, driverFaceRecognition *model.DriverFaceRecognition) error
	GetByDriverID(ctx context.Context, driverID int64) (*model.DriverFaceRecognition, error)
	IsTodayRecognized(ctx context.Context, driverID int64) (bool, error)
}

type driverFaceRecognitionDao struct {
	*MysqlClient
}

func NewDriverFaceRecognitionDao(
	r *MysqlClient,
) DriverFaceRecognitionDao {
	return &driverFaceRecognitionDao{
		MysqlClient: r,
	}
}

func (r *driverFaceRecognitionDao) Create(ctx context.Context, driverFaceRecognition *model.DriverFaceRecognition) error {
	if err := r.DB(ctx).Create(driverFaceRecognition).Error; err != nil {
		r.logger.WithContext(ctx).Error("customerLoginLogDao|Create(", zap.Any("data", map[string]interface{}{
			"driverFaceRecognition": driverFaceRecognition,
		}), zap.Error(err))
		return err
	}
	return nil
}

func (r *driverFaceRecognitionDao) GetByDriverID(ctx context.Context, driverID int64) (*model.DriverFaceRecognition, error) {
	var driverFaceRecognition model.DriverFaceRecognition
	if err := r.DB(ctx).Where("driver_id = ?", driverID).First(&driverFaceRecognition).Error; err != nil {
		r.logger.WithContext(ctx).Error("driverFaceRecognitionDao|GetDriverFaceRecognition(", zap.Any("data", map[string]interface{}{
			"driverID": driverID,
		}), zap.Error(err))
		return nil, err
	}
	return &driverFaceRecognition, nil
}

func (r *driverFaceRecognitionDao) IsTodayRecognized(ctx context.Context, driverID int64) (bool, error) {
	var driverFaceRecognition model.DriverFaceRecognition
	var cnt int64
	now := time.Now()
	err := r.DB(ctx).Model(&driverFaceRecognition).
		Where("driver_id = ?", driverID).
		Where("face_date = ?", time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)).
		Count(&cnt).Error
	if err != nil {
		r.logger.WithContext(ctx).Error("driverFaceRecognitionDao|GetDriverFaceRecognition(", zap.Any("data", map[string]interface{}{
			"driverID": driverID,
		}), zap.Error(err))
		return false, err
	}
	return cnt != 0 , nil
}

